<?php
namespace App\Admin\Controllers\Consultation;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Encore\Admin\Facades\Admin;
use Illuminate\Http\Request;
use App\Admin\Controllers\Common\Common;
use Chumper\Zipper\Zipper;


class StController extends Controller {
	public function index(Request $request) {
		return view("admin.consultation.st.index",[
			"Status" => $request->get("status")
		]);
	}

	public function getData(Request $request) {
		try {
			$params = $request->all();
			$offset = ($params['page']['pageNumber'] - 1) * $params['page']['pageSize'];
			$data = [];
			$data['total'] = $this->mkWhereSQL($params)->count();
			$data['rows'] = $this->mkWhereSQL($params)
				->orderBy($params['sort']['sortBy'],$params['sort']['orderBy'])
				->limit($params['page']['pageSize'])->offset($offset)->get([
					'*',DB::raw('CEIL(DATEDIFF(NOW(),birthday)/365) as age')
				]);
			return ['code'=>1,'msg'=>"数据获取成功","data"=>$data];
		} catch (\Exception $e) {
			return ['code'=>0,'msg'=>"faild:".$e->getMessage(),"data"=>""];
		}
	}
	private function mkWhereSQL($params) {
		$db = DB::table("consultation_st");
		if($params['enroll_at']){
			$db->whereBetween('enroll_at',[
				$params['enroll_at']." 00:00:00",
				$params['enroll_at']." 23:59:59"
			]);
		}
		if($params['primary_phone']){
			$db->where('primary_phone',"like","%".$params['primary_phone']."%");
		}
		if($params['name']){
			$db->where('name',"like","%".$params['name']."%");
		}
		if($params['primary_parent_name']){
			$db->where('primary_parent_name',"like","%".$params['primary_parent_name']."%");
		}
		if($params['step']){
			$db->where('step',"=",$params['step']);
		}
		if($params['status']){
			$db->where('status',"=",$params['status']);
		}
		return $db;
	}

	public function destroy(Request $request) {
		DB::beginTransaction();
		try {
			DB::table("consultation_st")->whereIn("id",$request['ids'])->delete();
			DB::commit();
			return ['code'=>1,'msg'=>'删除成功','data'=>''];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'删除失败，请稍后...'.$e->getMessage(),'data'=>''];
		}
	}

	public function changeStatus(Request $request) {
		DB::beginTransaction();
		try {
			DB::table("consultation_st")->whereIn("id",$request['ids'])->update([
				"status" => $request->get("status")
			]);
			DB::commit();
			return ['code'=>1,'msg'=>'操作成功','data'=>''];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'操作失败，请稍后...'.$e->getMessage(),'data'=>''];
		}
	}

	public function exportData(Request $request,Zipper $zipper) {
		try {
			$limit = 500;
			$type = $request['export_type'];
			$whereStatus = $request['where_status'];
			$db = DB::table("consultation_st");
			$opt = [
				"header" => [
					'序号','姓名','年龄','性别','主要家长','主要联系方式','入学时间','阶段','状态'
				],
				'sheetname' => "sheet0",
				"save_path" => public_path()."/excel/",
				"file_name" => "consultation_st_".Admin::user()->id."_".date("ymdHis"),
			];
			if($type != "all"){
				$db->whereIn("id",explode(",",$request['ids']));
				$status = "done";
			}else{
				$offset = $request['offset'];
				$count = DB::table("consultation_st")->count();
				$status = ($offset+1)*$limit < $count ? "doing" : "done";
				$db->where("status",'=',$whereStatus)->limit($limit)->offset($request['offset'] * $limit);
				$opt['file_name'] = "consultation_st_all_".Admin::user()->id."_".$offset;
			}
			$data = json_decode(json_encode($db->get([
				'id','name',DB::raw('CEIL(DATEDIFF(NOW(),birthday)/365) as age'),
				'sex','primary_parent_name','primary_phone',
				'enroll_at','step','status'
			])),true);
			foreach($data as &$v){
				$v['primary_phone'] .= "\t";
			}
			$url = Common::exportToExcel($data,$opt);
			if( $type == "all" && $status == "done" && $offset != 0) {
				$file_arr = [];
				for($i=0;$i<=$offset;$i++) {
					$file_arr[] = $opt['save_path']."consultation_st_all_".Admin::user()->id."_".$i.".xls";
				}
				$zip_name = "consultation_st_all_".Admin::user()->id.".zip";
				$zip_path = $opt['save_path'].$zip_name;
				$zipper->make($zip_path)->add($file_arr)->close();
				$url = $zip_name;
			}
			$return = [
				'status' => $status,'fileName' => $url
			];
			return ['code'=>1,'msg'=>'success','data'=>$return];
		} catch (\Exception $e) {
			return ['code'=>0,'msg'=>"faild:".$e->getMessage(),"data"=>""];
		}
	}
}
